import datetime

from django.core.management.base import BaseCommand
from django.conf import settings

from account.models import User
from system.models import Organization, Menu
from system.services import encrypt_service
from connection.services import connection_service
from connection.models import Partner, PartnerType
from libs.enums import ConnectionState, SystemAppKey


class Command(BaseCommand):
    help = '系统初始化'

    def handle(self, *args, **options):
        print('开始初始化...')
        self.init_super_admin()
        self.init_menu()
        self.init_organization()
        self.init_encrypt()
        self.init_wwexx()
        print('初始化完成')

    def init_super_admin(self, *args, **options):
        print('开始初始化超级管理员...')
        user = User.objects.filter(
            is_superuser=True
        ).first()
        if user:
            print('系统已存在超级管理员，无需重复初始化')
            return
        user = User(
            username='admin',
            name='管理员',
            is_superuser=True,
            is_staff=True
        )
        user.set_password('admin')
        user.save()
        print('初始化超级管理员完成，账号: admin，密码: admin，请及时修改密码')

    def init_menu(self, *args, **options):
        print('开始初始化菜单...')
        if Menu.objects.exists():
            print('菜单已初始化，无需重复初始化')
            return

        items = [
            {
                'id': 1,
                'name': 'dashboard',
                'parent_id': None,
                'title': '首页',
                'path': '/dashboard',
                'component': 'wex/dashboard/index.vue',
                'orderNo': 100,
                'icon': 'ant-design:dashboard-outlined'
            },

            {
                'id': 2,
                'name': 'connectionPage',
                'parent_id': None,
                'title': '企业互联',
                'path': '/connection',
                'component': 'LAYOUT',
                'orderNo': 200,
                'icon': 'ant-design:link-outlined',
                'permissions': []
            },
            {
                'id': 3,
                'name': 'connectionIndex',
                'parent_id': 2,
                'title': '互联管理',
                'path': 'index',
                'component': 'wex/connection/index.vue',
                'orderNo': 100,
                'icon': '',
                'permissions': ['connection-view', 'connection-manage']
            },
            {
                'id': 4,
                'name': 'connectionDataConfig',
                'parent_id': 2,
                'title': '数据配置',
                'path': 'entity',
                'component':
                'wex/entity/index.vue',
                'orderNo': 200,
                'icon': '',
                'permissions': ['model-view', 'model-manage']
            },
            {
                'id': 5,
                'name': 'connectionTemplate',
                'parent_id': 2,
                'title': '授权模板',
                'path': 'certificate-template',
                'component': 'wex/certificateTemplate/index.vue',
                'orderNo': 300,
                'icon': '',
                'permissions': ['template-view', 'template-manage']
            },

            {
                'id': 6,
                'name': 'dataCenterPage',
                'parent_id': None,
                'title': '数据中心',
                'path': '/data-center',
                'component': 'LAYOUT',
                'orderNo': 300,
                'icon': 'ant-design:database-outlined',
                'permissions': []
            },
            {
                'id': 7,
                'name': 'dataCenterConnectionData',
                'parent_id': 6,
                'title': '互联数据',
                'path': 'index',
                'component': 'wex/datacenter/index.vue',
                'orderNo': 100,
                'icon': '',
                'permissions': ['data-center-view']
            },
            {
                'id': 8,
                'name': 'dataCenterMyData',
                'parent_id': 6,
                'title': '我的数据',
                'path': 'me',
                'component': 'wex/datacenter/me.vue',
                'orderNo': 200,
                'icon': '',
                'permissions': ['data-center-view']
            },

            {
                'id': 9,
                'name': 'organizationManage',
                'parent_id': None,
                'title': '企业管理',
                'path': '/organization',
                'component': 'wex/organization/index.vue',
                'orderNo': 400,
                'icon': 'ant-design:apartment-outlined',
                'permissions': ['organization-view', 'organization-manage']
            },

            {
                'id': 10,
                'name': 'taskPage',
                'parent_id': None,
                'title': '任务调度',
                'path': '/task',
                'component': 'LAYOUT',
                'orderNo': 500,
                'icon': 'ant-design:schedule-outlined',
                'permissions': []
            },
            {
                'id': 11,
                'name': 'taskManage',
                'parent_id': 10,
                'title': '任务调度',
                'path': 'index',
                'component': 'wex/task/index.vue',
                'orderNo': 100,
                'icon': '',
                'permissions': ['task-view', 'task-manage']
            },
            {
                'id': 12,
                'name': 'taskLog',
                'parent_id': 10,
                'title': '执行日志',
                'path': 'log',
                'component': 'wex/taskLog/index.vue',
                'orderNo': 200,
                'icon': '',
                'permissions': ['task-view', 'task-manage']
            },

            {
                'id': 13,
                'name': 'appPage',
                'parent_id': None,
                'title': '应用管理',
                'path': '/app',
                'component': 'LAYOUT',
                'orderNo': 600,
                'icon': 'ant-design:appstore-add-outlined',
                'permissions': []
            },
            {
                'id': 14,
                'name': 'pageManage',
                'parent_id': 13,
                'title': '应用管理',
                'path': 'index',
                'component': 'wex/app/index.vue',
                'orderNo': 100,
                'icon': '',
                'permissions': ['app-manage']
            },
            {
                'id': 15,
                'name': 'app',
                'parent_id': 13,
                'title': '应用',
                'path': ':id',
                'component': 'wex/app/AppPage.vue',
                'orderNo': 200,
                'icon': '',
                'permissions': ['app-manage'],
                'hideMenu': True
            },

            {
                'id': 16,
                'name': 'systemPage',
                'parent_id': None,
                'title': '系统管理',
                'path': '/system',
                'component': 'LAYOUT',
                'orderNo': 700,
                'icon': 'ion:settings-outline',
                'permissions': []
            },
            {
                'id': 17,
                'name': 'orgInfo',
                'parent_id': 16,
                'title': '企业信息',
                'path': 'index',
                'component': 'wex/system/system/index.vue',
                'orderNo': 100,
                'icon': '',
                'permissions': ['organization-info-manage']
            },
            {
                'id': 18,
                'name': 'encrypt',
                'parent_id': 16,
                'title': '密钥管理',
                'path': 'key',
                'component': 'wex/system/key/index.vue',
                'orderNo': 200,
                'icon': '',
                'permissions': ['encrypt-manage']
            },
            {
                'id': 19,
                'name': 'user',
                'parent_id': 16,
                'title': '用户管理',
                'path': 'user',
                'component': 'wex/system/user/index.vue',
                'orderNo': 300,
                'icon': '',
                'permissions': ['user-manage']
            },
            {
                'id': 20,
                'name': 'role',
                'parent_id': 16,
                'title': '角色管理',
                'path': 'role',
                'component': 'wex/system/role/index.vue',
                'orderNo': 400,
                'icon': '',
                'permissions': ['role-manage']
            },
            {
                'id': 21,
                'name': 'menu',
                'parent_id': 16,
                'title': '菜单管理',
                'path': 'menu',
                'component': 'wex/system/menu/index.vue',
                'orderNo': 500,
                'icon': '',
                'permissions': ['role-manage']
            },
            {
                'id': 22,
                'name': 'userProfile',
                'parent_id': 16,
                'title': '个人资料',
                'path': 'profile',
                'component': 'wex/system/profile/index.vue',
                'orderNo': 600,
                'icon': '',
                'permissions': []
            },
            {
                'id': 23,
                'name': 'password',
                'parent_id': 16,
                'title': '修改密码',
                'path': 'password',
                'component': 'wex/system/password/index.vue',
                'orderNo': 700,
                'icon': '',
                'permissions': []
            },
            {
                'id': 24,
                'name': 'deploy',
                'parent_id': 16,
                'title': '系统部署',
                'path': 'deploy',
                'component': 'wex/system/deploy/index.vue',
                'orderNo': 800,
                'icon': '',
                'permissions': []
            },
            {
                'id': 25,
                'name': 'operationLog',
                'parent_id': 16,
                'title': '操作记录',
                'path': 'log',
                'component': 'wex/system/log/index.vue',
                'orderNo': 900,
                'icon': '',
                'permissions': ['operation-log-view']
            },

            {
                'id': 26,
                'name': 'pluginPage',
                'parent_id': None,
                'title': '扩展管理',
                'path': '/plugin',
                'component': 'LAYOUT',
                'orderNo': 800,
                'icon': 'ant-design:appstore-add-outlined',
                'permissions': []
            },
            {
                'id': 27,
                'name': 'pluginList',
                'parent_id': 26,
                'title': '扩展列表',
                'path': 'index',
                'component': 'wex/plugin/index.vue',
                'orderNo': 100,
                'icon': '',
                'permissions': []
            },
            {
                'id': 28,
                'name': 'pluginInstalled',
                'parent_id': 26,
                'title': '安装管理',
                'path': 'installed',
                'component': 'wex/plugin/installed.vue',
                'orderNo': 200,
                'icon': '',
                'permissions': []
            },
            {
                'id': 29,
                'name': 'pluginInstalledPlugins',
                'parent_id': 26,
                'title': '已安装扩展',
                'path': 'installed-plugins',
                'component': '',
                'orderNo': 300,
                'icon': '',
                'permissions': []
            }
        ]
        for item in items:
            Menu.objects.create(**item)
        print('初始化菜单完成')

    def init_organization(self, *args, **options):
        print('开始初始化系统企业...')
        if Organization.objects.exists():
            print('已存在系统企业，无需重复初始化')
            return
        Organization.objects.create(
            name='默认名称'
        )
        print('初始化系统企业完成, 名称为默认名称，请在平台配置')

    def init_encrypt(self, *args, **options):
        print('开始初始化系统密钥...')
        instance = encrypt_service.get()
        if instance:
            print('已存在系统密钥，无需重复初始化')
            return
        encrypt_service.reset_encrypt_key()
        print('初始化系统密钥完成')

    def init_wwexx(self, *args, **options):
        print('初始化WWEXX应用...')
        if Partner.objects.filter(type=PartnerType.APP.value, app_server=settings.WWEXX_SERVER).exists():
            print('无需重复初始化')
            return
        try:
            partner = connection_service.create_app_parnter(settings.WWEXX_SERVER, system_app_key=SystemAppKey.WWEXX.value)
        except Exception:
            print('初始化WWEXX应用失败，请稍后重试')
            return
        start_time = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
        end_time = datetime.datetime(2099, 12, 31, 23, 59, 59, 999999)
        connection_service.create_connection(
            partner=partner,
            state=ConnectionState.ONGOING.value,
            start_time=start_time,
            end_time=end_time
        )
        print('初始化WWEXX应用完成')
